package com;

import java.io.File;
import java.io.FileInputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class Env {
	private static final String envPath = "D:/work/workspace/daenong/www/WEB-INF/conf/env.properties";
	//private static final String envPath = "/www/WEB-INF/conf/env.properties";
	private static long lastModified = -1;
	public static Map __env;
	
	static {
		reload();
	}
	
	public static String get(String key) {
		return get(key, "utf-8");
	}
	
	public static String get(String key, String encoding) {
		Object value = __env.get(key);
		
		if (value == null) return null;

		try {
			return new String(((String) value).getBytes("ISO8859_1"), encoding);
		} catch (Exception e) {
			System.out.println("Error in encoding charset [" + value + "][" + encoding + "]");
			return null;
		}
	}

	public synchronized static void reload() {
		File envFile = new File(envPath);

		// Does env file exist?
		if (!envFile.isFile()) {
			System.out.println("Can't find env file from [" + envFile.getAbsolutePath() + "]");
			return;
		}

		// Have we read the config ?
		if (lastModified == envFile.lastModified()) return;
		
		lastModified = envFile.lastModified();
		setEnv(envFile);
	}
	
	protected static void setEnv(File envFile) {
		Properties property = new Properties();
		
		try {
			property.load(new FileInputStream(envFile));
		} catch (Exception e) {
			System.out.println("Error in loading properties [" + envFile.getAbsolutePath() + "]");
			return;
		}

		Map newEnv = new HashMap();
		Object key;
		
		for (Enumeration e = property.keys(); e.hasMoreElements();) {
			key = e.nextElement();
			newEnv.put(key, property.get(key));
		}
		__env = newEnv;
	}	
}
